﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="PageTitle" runat="server">
    <title>信件</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageStyles" runat="server">
    <style type="text/css">
        .cmbHasConfirm
        {
            font-size: 14px;
            color: #090;
        }
        
        .cmbHasNotConfirm
        {
            font-size: 14px;
            color: #999;
        }
        
        #replyInfo
        {
            background-color: #F0F5F8;
            background-repeat: no-repeat;
            clear: both;
            word-wrap: break-word;
            min-height: 50px;
            margin-bottom: 2px;
            width: 100%;
        }
        #avatar
        {
            margin-left: 5px;
        }
    </style>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PageScripts" runat="server">
    <script type="text/javascript">
    //************* URL常量

    var URL_MESSAGE_CONFIRMMESSAGE = '/message/ConfirmMessage';
    var URL_MESSAGE_REPLYTOPIC = '/message/ReplyTopic';
    var URL_MESSAGE_REPLYSINGLEMESSAGE = '/message/ReplySingleMessage';

    //************* 全局变量

    var g_Var = {
        'topicInfo': null,
        'currentTime': null,
        'messageId': null,
        'toReplyName': null,
        'currentUserID': null
    };

    //************* 常量定义

    //************* Accessor访问器

    var EzAccessor = {};
        var realAccessor = {
            'doReplyTopic': function (topicId, currentUser) {
                var replyText = $('#replyContent').val().htmlEncode();
                var topicId = topicId;

                var isReplyToAll = false;
                if ($('#isReplyToAll').attr("checked") == true) {
                    isReplyToAll = true;
                }

                $(document).ajaxBusy('begin');
                $.post(URL_MESSAGE_REPLYTOPIC, {
                    'replyText': replyText,
                    'topicId': topicId,
                    'isReplyToAll': isReplyToAll
                }, function (e) {
                    if (e.Status == "Success") {
                        replyCompleted(currentUser);
                    }
                    $(document).ajaxBusy('end');
                });

            },

            'doReplySingleMessage': function (topicId, currentUser) {
                var replyText = $('#replyContent').val().htmlEncode();
                var topicId = topicId;
                var messageId = g_Var['messageId'];

                var isReplyToAll = false;
                if ($('#isReplyToAll').attr("checked") == true) {
                    isReplyToAll = true;
                }

                $.post(URL_MESSAGE_REPLYSINGLEMESSAGE, {
                    'messageId': messageId,
                    'topicId': topicId,
                    'replyText': replyText,
                    'isReplyToAll': isReplyToAll
                }, function (e) {
                    if (e.Status == "Success") {
                        //增添留言
                        replyCompleted(currentUser);
                    }
                    $(this).ajaxBusy('end');
                });

            },
            
            'getMessage': function () {
                return <%= ViewData["Message"] %>;
            },
            'getCurrentUser': function () {
                return <%= ViewData["CurrentUser"] %>;
            },
            'getBasicInfo': function () {
                g_Var['currentTime'] = Date.fromEpoch(<%= ViewData["CurrentTime"] %>);
            }
        }
        EzAccessor = realAccessor;


    ///传入一个ddContainer
    ///返回姓名
    function getName(container) {
        return name = $(container).find('.senderName').text();
    }
    
    //增添回复内容
    function addReplyDom(messageId, text, replyTime, senderId, senderName, deptName, isHighlight) {
        var replyHtmlStrTpl = '<dd id="{messageId}" style="width:430px; height:50px; border-bottom: 1px solid #ffffff; margin-left: 10px;">' +
                                  '<div style="float: left;"><img height="48" width="48" src="/core/headicon/{senderId}"></img></div>' +
                                  '<div style=" margin-left: 55px;">' +
                                    '<span class="senderName" style="font-size: 16px; color:#2583AD;">{name}</span>' +
                                    '<span class="deptName">({deptName})</span>' +
                                    '<span style="font-size: 12px; color: Gray;"> {time}</span>' +
                                    '<p class="msgContent" style="font-size: 14px; color: #000000">{message}&nbsp;</p>' +
                                  '</div>' +
                              '</dd>';

        replyHtmlStrTpl = replyHtmlStrTpl.replace("{message}", text)
                                          .replace("{messageId}", messageId)
                                          .replace("{time}", replyTime)
                                          .replace("{name}",
                                           senderName)
                                          .replace("{deptName}", deptName)
                                          .replace('id="undefined"', "")
                                          .replace("{senderId}", senderId);

        var replyHtml = $(replyHtmlStrTpl)
             .appendTo('#replyInfo');


        var btnReplayClick = function () {

            ///获得回复人姓名
            g_Var.toReplyName = getName(replyHtml);
            //获得该回复ID
            g_Var.messageId = $(replyHtml).attr("id");

            var replyMark = "回复" + g_Var.toReplyName + ": ";
            $("#replyContent")
              .focus()
              .val(replyMark);
              
        };

        //自己发送的回复内容自己不能回复
        if (senderId != g_Var.currentUserID) {
            var replyLink = $('<a class="highlight">回复</a>');
            replyLink.click(btnReplayClick);
            replyHtml.find('.msgContent').append(replyLink);
        }

        if (isHighlight) {
            replyHtml.highlight();
        }

    }



    //增添回复
    function replyCompleted(currentUser) {
        $('#replyContainer').show();
        //传入一个空的messageId
        var messageId;
        var text = $('#replyContent').val().htmlEncode();
        var replyTime = g_Var['currentTime'].toShortDateTime();
        var senderName = currentUser.Name;
        var senderId = currentUser.Id;
        var deptName = currentUser.Dept.DeptName;
        //增添这条回复内容
        addReplyDom(messageId, text, replyTime, senderId, senderName, deptName, true);

        $('#replyContent')
            .clearFields()
            .focus();
    }

    ///显示收件人列表
    function showNameList(message) {
        $('#tbl_nameList').empty();
        
        if(message.NeedConfirm){
            //需要确认的信件
            //获取已确认未确认名单
            var confirmNameList = message.ConfirmNameList;
            var notConfirmNameList = message.NotConfirmNameList;

            //已确认
            for (var key in confirmNameList) {
                var confirmManDom = '<p style="font-weight:bold;">{name}({deptName})</p><p class="cmbHasConfirm">已确认收到该信件</p>';
                confirmManDom = confirmManDom.replace("{deptName}", confirmNameList[key].Dept.DeptName)
                                             .replace("{name}", confirmNameList[key].Name);

                $('#tbl_nameList').append(confirmManDom);
            }

            //未确认
            for (var key in notConfirmNameList) {
                var notConfirmManDom = '<p  style="font-weight:bold;">{name}({deptName})</p><p class="cmbHasNotConfirm">尚未确认收到该信件</p>';
                notConfirmManDom = notConfirmManDom.replace("{deptName}", notConfirmNameList[key].Dept.DeptName)
                                                   .replace("{name}", notConfirmNameList[key].Name);

                $('#tbl_nameList').append(notConfirmManDom);
            }
        
        }else{
            //不需要确认的信件 
            //获取信件参与者名单
            for(var key in message.Participator.GroupParticipators){
                var groupList = message.Participator.GroupParticipators;
                var groupStr = '<p  style="font-weight:bold;">{groupName}</p>';
                groupStr = groupStr.replace("{groupName}", groupList[key].Description); 

                $('#tbl_nameList').append(groupStr);    
            }
            for(var key in message.Participator.UserParticipators){
                var simpleUserList = message.Participator.UserParticipators;
                var memberStr = '<p  style="font-weight:bold;">{name} ({deptName})</p>';
                memberStr = memberStr.replace("{deptName}", simpleUserList[key].Dept.DeptName)
                                     .replace("{name}", simpleUserList[key].Name);

                $('#tbl_nameList').append(memberStr);    
            }
        
        }


    }



    ///显示信件内容
    function showMessage(messageInfo) {
        var time = Date.fromEpoch(messageInfo.CreateOn);
        var CreateOn = time.toShortDateTime();
        var deptName = messageInfo.SenderUser.Dept.DeptName;
        var senderName = messageInfo.SenderUser.Name;
        var userId = messageInfo.SenderUser.Id;
        var userPhoto = '<img height="48" width="48" src="/core/headicon/{userId}"></img>';
        var confirmNumber  = messageInfo.ConfirmNumer;

        userPhoto = userPhoto.replace("{userId}", userId);

        $('#topicTitle').html(messageInfo.Title);
        $('#sendName').html(senderName);
        $('#deptName').html("(" + deptName + ")");
        $('#sendTime').html(CreateOn);
        $('#messageContent').html(messageInfo.Text);
        $('#avatar').html(userPhoto);

        if(messageInfo.NeedConfirm){
            var confirmNumberStr = '需要确认的信件 ({number} 个人已确认)';
            confirmNumberStr = confirmNumberStr.replace("{number}", confirmNumber)
            $('#confrimNum').html(confirmNumberStr);
        }

    }


  

    ///显示回复列表
    function showReply(replyList) {

        if (replyList.length == 0) {
            $('#replyContainer').hide();
        } else {
            for (var key in replyList) {
                var time = Date.fromEpoch(replyList[key].CreateOn);
                var replyTime = time.toShortDateTime();
                var senderName = replyList[key].SenderUser.Name;
                var senderId = replyList[key].SenderUser.Id;
                var deptName = replyList[key].SenderUser.Dept.DeptName;
                var messageId = replyList[key].MessageId;
                var text = replyList[key].Text;

                addReplyDom(messageId, text, replyTime, senderId, senderName, deptName);
            }
        }

    }



    //验证回复内容是否为空
    function isEmpty(str) {
        if (str.trim() == "") {
            var statusInfo = { 'Status': 'Error', 'Info': '回复不能为空!', 'Date': null };
            $.displayStatusInfo(statusInfo);

            return true;
        }
        return false;
    }


    function initTime() {
        $(this).ajaxBusy();
        EzAccessor.getBasicInfo();
        var updateCurrentDateTime = function () {
            //从后台接受时间数
            var date = g_Var['currentTime'].toFullChineseDateFormat();
            var time = g_Var['currentTime'].toFullTimeFormat();


        }

        var refreshCurrentTime = function () {
            // 时间加1
            g_Var['currentTime'] = new Date(
				g_Var['currentTime'].getFullYear(),
				g_Var['currentTime'].getMonth(),
				g_Var['currentTime'].getDate(),
				g_Var['currentTime'].getHours(),
				g_Var['currentTime'].getMinutes(),
				g_Var['currentTime'].getSeconds() + 1
				);

            updateCurrentDateTime();
        }

        refreshCurrentTime();
        setInterval(refreshCurrentTime, 1000);
    }




    function initPageEvent() {
        var currentUser = EzAccessor.getCurrentUser();
        $('#btnSubmit').click(function () {
            var replyContent = $('#replyContent').val();
            var toReplyString = "回复" + g_Var.toReplyName + ":";
            var isReplayToSingle = replyContent.startWith(toReplyString);

            var msgIsEmptyOrNot = isEmpty(replyContent);

            if (!msgIsEmptyOrNot) {
                //是回复给单个人
                if (g_Var.toReplyName && isReplayToSingle) {

                    EzAccessor.doReplySingleMessage(g_Var.topicInfo.Id, currentUser);
                }
                else {

                    EzAccessor.doReplyTopic(g_Var.topicInfo.Id, currentUser);
                }
            }

        });

        $('#btnConfirmMessage').click(function () {
            //todo:
            var topicId = g_Var.topicInfo.Id;
            //确认该信件
            window.location.href = '/message/confirmMessage?topicId=' + topicId;
        });
    }




    function initPage() {
        g_Var.topicInfo = EzAccessor.getMessage();
        var replyList = g_Var.topicInfo.ReplyList;
        var isDisplayConfirmNow = g_Var.topicInfo.IsDisplayConfirmNow;
        var isDisplayHasConfirmed = g_Var.topicInfo.IsDisplayHasConfirmed;

        var curretnUser = EzAccessor.getCurrentUser();
        g_Var.currentUserID = curretnUser.Id;
        
        $('#tip_nameList').eztips();
        
        $('#status-panel').hide();

        if(isDisplayHasConfirmed){
           $('#tip_HasConfirmed').eztips();
        }
        
        //该信件是否已经确认 
        if (isDisplayConfirmNow) {
           $('#status-panel').show();
        }

        
        showNameList(g_Var.topicInfo);
        showMessage(g_Var.topicInfo);
        showReply(replyList);

    }
    
    $(function () {
        initPage();
        initPageEvent();
        initTime();

    });
    
    </script>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PageHead" runat="server">
    <%
        Html.RenderPartial("_sayHello"); %>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="PageContent" runat="server">
    <div style="display: block;" class="status-warning" id="status-panel">
        <span>您尚未确认收到该信件</span>
        <div class="status-panel-funcs">
            <a id="btnConfirmMessage">立即确认收到</a></div>
    </div>
    <div id="page-head" class="page-head">
        <div style="overflow: hidden; position: relative;">
            <div style="float: left;">
                <p id="topicTitle" style="font-size: 16px; font-weight: bold; min-height: 20px;">
                </p>
                <p id="sendTime" style="font-size: 12px;">
                </p>
                <p id="confrimNum" style="color: Red; font-size: 14px;">
                </p>
            </div>
            <div style="float: right;">
                <span id="sendName" style="color: #2583AD;">&nbsp;</span><span id="deptName"></span><span
                    id="avatar"></span>
            </div>
        </div>
    </div>
    <div id="page-body">
        <div>
            <div id="messageContent" style="font-size: 16px;">
            </div>
        </div>
        <div id="replyContainer" style="margin: 10px 0px 0px 5px;">
            <hr />
            <dl id="replyInfo">
            </dl>
        </div>
        <hr />
        <div id="textInfo" style="margin-top: 20px">
            <textarea id="replyContent" rows="5" style="margin-left: 20px; width: 450px" name="p_replyContentContent"></textarea>
        </div>
    </div>
    <div class="page-submit">
        <div id="btnSubmit">
            回复</div>
        <script type="text/javascript">
            $(function () {
                $("#btnSubmit").button({
                    icons: {
                        primary: "ui-icon-comment"
                    },
                    text: true
                });
            });
        </script>
        <label id="lblClicked" for="isReplyToAll">
            <input type="checkbox" id="isReplyToAll" />回复所有人
        </label>
    </div>
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="PageShortcut" runat="server">
    <div id="shortcuts" class="box">
        <a id="btn-newmessage" style="width: 100%;" href="/message/send">写新信件</a>
        <script type="text/javascript">
            $(function () {
                $("#btn-newmessage").button({
                    icons: {
                        primary: "ui-icon-mail-closed"
                    },
                    text: true
                });
            });
        </script>
    </div>
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="PageFoot" runat="server">
    <div id="tip_HasConfirmed" style="display: none;" class="tip-info">
        <h1>
            您已经确认过该信件</h1>
    </div>
    <div id="tip_nameList" style="display: none;">
        <h1>
            该信件发送给:</h1>
        <div id="tbl_nameList">
        </div>
    </div>
</asp:Content>
